package eu.dominicum.ft.ui.web.jsf.view.bean;

import eu.dominicum.ft.pd.TeamMember;
import eu.dominicum.ft.pd.boundary.FantasyTourManagement;
import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.event.SelectionEvent;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import java.util.List;

/**
 * Backing bean for the select-team-member-dialog view.
 *
 * @author Harry Klerks
 * @since 2013M1
 */
@ManagedBean(name = "selectTeamMemberDialog")
@ViewScoped
public final class SelectTeamMemberDialogBean {

    /**
     * {@link eu.dominicum.ft.pd.boundary.FantasyTourManagement}.
     */
    @Inject
    private FantasyTourManagement fantasyTourManagement;

    /**
     * Team members.
     */
    private List<TeamMember> teamMembers;

    /**
     * .
     *
     * @return List<TeamMember>
     */
    public List<TeamMember> getTeamMembers() {
        return teamMembers;
    }

    /**
     * .
     *
     * @param newTeamMembers -
     */
    public void setTeamMembers(final List<TeamMember> newTeamMembers) {
        this.teamMembers = newTeamMembers;
    }

    /**
     * Refreshes the list of team mebers.
     */
    private void refreshTeamMembers() {

        Long tourId = (Long) RequestContext.getCurrentInstance().getPageFlowScope().get("tourId");
        this.teamMembers = this.fantasyTourManagement.findAllTeamMembers(tourId);
    }

    /**
     * Initialiser.
     */
    @PostConstruct
    public void init() {

        this.refreshTeamMembers();
    }

    /**
     * Event handler that fires when the selection changes.
     *
     * @param selectionEvent -
     */
    public void onTeamMemberSelection(final SelectionEvent selectionEvent) {

        Integer selectedRow = (Integer) selectionEvent.getAddedSet().iterator().next();
        RequestContext.getCurrentInstance().returnFromDialog(this.teamMembers.get(selectedRow).getYerseyNumber(), null);
    }
}
